package com.agritech.mapper;

import com.agritech.entity.Knowledge;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 知识Mapper接口
 */
@Mapper
public interface KnowledgeMapper {
    
    /**
     * 根据分类ID查询知识列表
     * @param categoryId 分类ID
     * @return 知识列表
     */
    @Select("SELECT id,title, content, category_id as categoryId ,author_id as authorId, create_time as createTime,category_name categoryName,update_time as updateTime FROM knowledge WHERE category_id = #{categoryId}")
    List<Knowledge> selectByCategoryId(Long categoryId);

    /**
     * 根据关键词查询知识列表
     * @param keywords 关键词
     * @return 知识列表
     */
    @Select("SELECT id,title, content, category_id as categoryId ,author_id as authorId, create_time as createTime,category_name categoryName,update_time as updateTime FROM knowledge WHERE content LIKE CONCAT('%', #{keywords}, '%') OR title LIKE CONCAT('%', #{keywords}, '%')")
    List<Knowledge> list(@Param("keywords") String keywords);

    /**
     * 根据ID查询知识
     * @param id 知识ID
     * @return 知识对象
     */
    @Select( "SELECT id,title, content, category_id as categoryId ,author_id as authorId, create_time as createTime,category_name categoryName,update_time as updateTime FROM knowledge WHERE id = #{id}")
    Knowledge selectById(Long id);
    
    /**
     * 查询最新的知识
     * @param limit 查询数量
     * @return 知识列表
     */
    @Select( "SELECT id,title, content, category_id as categoryId , author_id as authorId, create_time as createTime,category_name categoryName,update_time as updateTime FROM knowledge ORDER BY create_time DESC LIMIT #{limit}")
    List<Knowledge> selectLatest(int limit);
    
    /**
     * 插入新知识
     * @param knowledge 知识对象
     * @return 影响行数
     */
    @Select( "INSERT INTO knowledge (title, content, category_id, author_id, create_time) VALUES (#{title}, #{content}, #{categoryId}, #{authorId}, #{createTime})")
    int insert(Knowledge knowledge);
    
    /**
     * 更新知识信息
     * @param knowledge 知识对象
     * @return 影响行数
     */
     @Update( "UPDATE knowledge SET title = #{title}, content = #{content} ,category_name = #{categoryName} WHERE id = #{id}")
    int update(Knowledge knowledge);
    
    /**
     * 根据ID删除知识
     * @param id 知识ID
     * @return 影响行数
     */
    @Select( "DELETE FROM knowledge WHERE id = #{id}")
    int delete(Long id);

    // KnowledgeMapper.java
    @Select("SELECT id,title, content,  category_id as categoryId ,author_id as authorId, create_time as createTime,category_name categoryName,update_time as updateTime  FROM knowledge LIMIT #{offset}, #{pageSize}")
    List<Knowledge> getKnowledgeList(@Param("offset") int offset, @Param("pageSize") int pageSize);
}    